// ELEVATE - 高端生活管理助手 JavaScript

// 高级励志话语数据库
const luxuryInspirationalQuotes = [
    "每一个伟大的梦想都始于一个敢于追求的人。今天，让我们继续前行。",
    "成功不是终点，失败也不是终结，唯有继续前进的勇气才是最重要的。",
    "你今天的努力，是幸运的伏笔；当下的付出，是明日的花开。",
    "不要等待机会，而要创造机会。你的未来掌握在自己手中。",
    "每一次的坚持，都在为更好的自己铺路。",
    "相信自己，你比想象中更强大。",
    "今天的一小步，是明天飞跃的基石。",
    "优秀是一种习惯，让我们从今天开始养成。",
    "困难是成长路上的垫脚石，而不是绊脚石。",
    "专注当下，享受过程，成功自然而然。",
    "真正的力量来自内心的坚定与对目标的执着。",
    "每个精彩的瞬间，都来自于不懈的努力和坚持。",
    "卓越不是一种行为，而是一种习惯。",
    "在追求梦想的路上，每一步都是成长的印记。",
    "最美的风景，总在最险峻的山峰之上。"
];

// 全局状态管理
const AppState = {
    currentPage: 'home',
    isLoading: false,
    touchStart: { x: 0, y: 0 },
    animationQueue: [],
    settings: {
        notifications: true,
        darkMode: false,
        cloudSync: true
    }
};

// DOM 元素选择器
const Elements = {
    pages: document.querySelectorAll('.premium-page'),
    navTabs: document.querySelectorAll('.luxury-nav-tab'),
    dailyQuoteElement: document.getElementById('daily-quote'),
    refreshQuoteBtn: document.getElementById('refresh-quote'),
    statusTime: document.querySelector('.premium-time'),
    habitCards: document.querySelectorAll('.premium-habit-card'),
    filterTabs: document.querySelectorAll('.luxury-filter-tab'),
    cycleBtns: document.querySelectorAll('.luxury-cycle-btn'),
    addBtns: document.querySelectorAll('.premium-add-btn, .premium-header-btn'),
    toggleSwitches: document.querySelectorAll('.luxury-toggle-switch input')
};

// 高端应用初始化
document.addEventListener('DOMContentLoaded', function() {
    console.log('🌟 ELEVATE - 高端生活管理助手启动中...');
    
    initializeLuxuryApp();
    setupAdvancedEventListeners();
    setupPremiumTouchHandlers();
    loadDailyInspiration();
    updateTimeDisplay();
    animateLuxuryAppLaunch();
    
    console.log('✨ 高端应用启动完成');
});

// 奢华应用初始化
function initializeLuxuryApp() {
    // 显示默认页面
    showPremiumPage('home');
    
    // 加载用户数据
    loadUserPreferences();
    
    // 设置高级状态栏更新
    setInterval(updatePremiumStatusBar, 1000);
    
    // 初始化高级触觉反馈
    if ('vibrate' in navigator) {
        console.log('✅ 高级触觉反馈系统已启用');
    }
    
    // 设置PWA支持
    if ('serviceWorker' in navigator) {
        console.log('✅ PWA高级支持检测完成');
    }
    
    // 初始化背景动画
    initializeBackgroundAnimations();
}

// 高级事件监听器设置
function setupAdvancedEventListeners() {
    // 奢华底部导航切换
    Elements.navTabs.forEach(tab => {
        tab.addEventListener('click', function(e) {
            e.preventDefault();
            const pageId = this.dataset.page;
            switchToPremiumPage(pageId);
            updateActiveNavigation(this);
            createLuxuryHapticFeedback();
            createNavTabAnimation(this);
        });
    });
    
    // 精致励志话语刷新
    if (Elements.refreshQuoteBtn) {
        Elements.refreshQuoteBtn.addEventListener('click', function(e) {
            e.preventDefault();
            createRotationAnimation(this);
            setTimeout(() => {
                loadDailyInspiration(true);
                createLuxuryHapticFeedback();
                createSparkleEffect(this);
            }, 300);
        });
    }
    
    // 精英习惯打卡系统
    document.addEventListener('change', function(e) {
        if (e.target.type === 'checkbox' && e.target.closest('.premium-habit-card')) {
            handleLuxuryHabitToggle(e.target);
        }
    });
    
    // 智能设置开关
    Elements.toggleSwitches.forEach(toggle => {
        toggle.addEventListener('change', function() {
            handlePremiumSettingChange(this);
        });
    });
    
    // 豪华项目筛选
    Elements.filterTabs.forEach(btn => {
        btn.addEventListener('click', function() {
            updateLuxuryFilterTabs(this);
            filterLuxuryProjects(this.textContent.trim());
            createLuxuryHapticFeedback();
            createFilterAnimation(this);
        });
    });
    
    // 智能周期任务操作
    Elements.cycleBtns.forEach(btn => {
        btn.addEventListener('click', function() {
            toggleLuxuryCycleTask(this);
        });
    });
    
    // 高端添加按钮
    Elements.addBtns.forEach(btn => {
        btn.addEventListener('click', function() {
            showLuxuryAddModal();
            createLuxuryHapticFeedback();
            createPulseAnimation(this);
        });
    });
}

// 高级触摸手势系统
function setupPremiumTouchHandlers() {
    const luxuryContent = document.querySelector('.luxury-content');
    
    // 触摸开始
    luxuryContent.addEventListener('touchstart', function(e) {
        AppState.touchStart.x = e.touches[0].clientX;
        AppState.touchStart.y = e.touches[0].clientY;
    });
    
    // 触摸结束 - 检测高级滑动手势
    luxuryContent.addEventListener('touchend', function(e) {
        if (!AppState.touchStart.x || !AppState.touchStart.y) return;
        
        const touchEndX = e.changedTouches[0].clientX;
        const touchEndY = e.changedTouches[0].clientY;
        
        const deltaX = AppState.touchStart.x - touchEndX;
        const deltaY = AppState.touchStart.y - touchEndY;
        
        // 左右滑动切换页面（优化阈值）
        if (Math.abs(deltaX) > Math.abs(deltaY) && Math.abs(deltaX) > 60) {
            if (deltaX > 0) {
                switchToNextPremiumPage();
            } else {
                switchToPreviousPremiumPage();
            }
            createLuxuryHapticFeedback('medium');
        }
        
        AppState.touchStart.x = 0;
        AppState.touchStart.y = 0;
    });
    
    // 防止页面弹跳
    luxuryContent.addEventListener('touchmove', function(e) {
        // 允许正常滚动，但防止过度滚动
        const target = e.target.closest('.luxury-content');
        if (target) {
            const scrollTop = target.scrollTop;
            const scrollHeight = target.scrollHeight;
            const clientHeight = target.clientHeight;
            
            if (scrollTop === 0 && deltaY > 0) {
                e.preventDefault();
            } else if (scrollTop + clientHeight >= scrollHeight && deltaY < 0) {
                e.preventDefault();
            }
        }
    });
}

// 高级页面切换系统
function showPremiumPage(pageId) {
    Elements.pages.forEach(page => {
        page.classList.remove('active');
    });
    
    const targetPage = document.getElementById(`${pageId}-page`);
    if (targetPage) {
        targetPage.classList.add('active');
        AppState.currentPage = pageId;
        
        // 高级页面切换动画
        createPageTransition(targetPage);
        
        // 更新页面特定功能
        updatePageSpecificFeatures(pageId);
    }
}

function switchToPremiumPage(pageId) {
    if (pageId === AppState.currentPage) return;
    
    showPremiumPage(pageId);
    createLuxuryHapticFeedback();
}

function switchToNextPremiumPage() {
    const pages = ['home', 'projects', 'profile'];
    const currentIndex = pages.indexOf(AppState.currentPage);
    const nextIndex = (currentIndex + 1) % pages.length;
    
    switchToPremiumPage(pages[nextIndex]);
    updateActiveNavigation(document.querySelector(`[data-page="${pages[nextIndex]}"]`));
}

function switchToPreviousPremiumPage() {
    const pages = ['home', 'projects', 'profile'];
    const currentIndex = pages.indexOf(AppState.currentPage);
    const prevIndex = (currentIndex - 1 + pages.length) % pages.length;
    
    switchToPremiumPage(pages[prevIndex]);
    updateActiveNavigation(document.querySelector(`[data-page="${pages[prevIndex]}"]`));
}

// 更新导航栏状态
function updateActiveNavigation(activeTab) {
    Elements.navTabs.forEach(tab => {
        tab.classList.remove('active');
    });
    if (activeTab) {
        activeTab.classList.add('active');
        createNavActiveAnimation(activeTab);
    }
}

// 加载每日精致灵感
function loadDailyInspiration(forceNew = false) {
    const today = new Date().toDateString();
    const savedQuote = localStorage.getItem('elevateAppDailyQuote');
    const savedDate = localStorage.getItem('elevateAppDailyQuoteDate');
    
    let quote;
    
    if (!forceNew && savedDate === today && savedQuote) {
        quote = savedQuote;
    } else {
        quote = luxuryInspirationalQuotes[Math.floor(Math.random() * luxuryInspirationalQuotes.length)];
        localStorage.setItem('elevateAppDailyQuote', quote);
        localStorage.setItem('elevateAppDailyQuoteDate', today);
    }
    
    if (Elements.dailyQuoteElement) {
        // 高级混出动画
        Elements.dailyQuoteElement.style.opacity = '0';
        Elements.dailyQuoteElement.style.transform = 'translateY(-10px)';
        
        setTimeout(() => {
            Elements.dailyQuoteElement.textContent = quote;
            Elements.dailyQuoteElement.style.transition = 'all 0.5s cubic-bezier(0.16, 1, 0.3, 1)';
            Elements.dailyQuoteElement.style.opacity = '1';
            Elements.dailyQuoteElement.style.transform = 'translateY(0)';
        }, 250);
    }
}

// 更新高级状态栏
function updatePremiumStatusBar() {
    const now = new Date();
    const timeString = now.toLocaleTimeString('zh-CN', { 
        hour: '2-digit', 
        minute: '2-digit',
        hour12: false 
    });
    
    if (Elements.statusTime) {
        Elements.statusTime.textContent = timeString;
    }
}

// 更新时间显示
function updateTimeDisplay() {
    const now = new Date();
    const options = { month: 'long', day: 'numeric' };
    const dateString = now.toLocaleDateString('zh-CN', options);
    
    const dateElement = document.querySelector('.premium-date-display');
    if (dateElement) {
        dateElement.textContent = dateString;
    }
}

// 处理高级习惯切换
function handleLuxuryHabitToggle(checkbox) {
    const habitCard = checkbox.closest('.premium-habit-card');
    const habitName = habitCard.querySelector('.habit-title').textContent;
    
    if (checkbox.checked) {
        habitCard.classList.add('completed');
        showLuxuryToast(`🎆 完成习惯："${habitName}"！`, 'success');
        
        // 更新连击数
        const streakElement = habitCard.querySelector('.streak-number');
        if (streakElement) {
            let currentStreak = parseInt(streakElement.textContent) || 0;
            streakElement.textContent = currentStreak + 1;
        }
        
        // 高级触觉反馈
        createLuxuryHapticFeedback('success');
        
        // 奢华完成动画
        playLuxuryCompletionAnimation(habitCard);
        
        // 更新状态徽章
        updateHabitStatusBadge(habitCard, 'completed');
        
    } else {
        habitCard.classList.remove('completed');
        showLuxuryToast(`习惯"${habitName}"已取消完成`, 'info');
        updateHabitStatusBadge(habitCard, 'pending');
    }
    
    // 更新统计
    updateLuxuryHabitStats();
    saveLuxuryHabitData();
}

// 播放奢华完成动画
function playLuxuryCompletionAnimation(element) {
    // 主动画
    element.style.transform = 'scale(1.02)';
    element.style.boxShadow = '0 12px 40px rgba(34, 197, 94, 0.4)';
    
    setTimeout(() => {
        element.style.transition = 'all 0.6s cubic-bezier(0.16, 1, 0.3, 1)';
        element.style.transform = 'scale(1)';
        element.style.boxShadow = '';
    }, 300);
    
    // 创建奢华庆祝粒子效果
    createLuxuryCelebrationParticles(element);
    
    // 添加光环效果
    createSuccessRippleEffect(element);
}

// 创建奢华庆祝粒子效果
function createLuxuryCelebrationParticles(element) {
    const rect = element.getBoundingClientRect();
    const centerX = rect.left + rect.width / 2;
    const centerY = rect.top + rect.height / 2;
    
    const particles = ['🎆', '✨', '🎉', '🔥', '⭐', '💫'];
    
    for (let i = 0; i < 8; i++) {
        const particle = document.createElement('div');
        particle.className = 'luxury-celebration-particle';
        particle.innerHTML = particles[Math.floor(Math.random() * particles.length)];
        
        const angle = (i / 8) * Math.PI * 2;
        const distance = 60 + Math.random() * 40;
        const endX = Math.cos(angle) * distance;
        const endY = Math.sin(angle) * distance;
        
        particle.style.cssText = `
            position: fixed;
            left: ${centerX}px;
            top: ${centerY}px;
            font-size: ${16 + Math.random() * 8}px;
            pointer-events: none;
            z-index: 1000;
            animation: luxuryCelebrationFloat 1.5s cubic-bezier(0.16, 1, 0.3, 1) forwards;
            --end-x: ${endX}px;
            --end-y: ${endY}px;
            animation-delay: ${i * 0.05}s;
        `;
        
        document.body.appendChild(particle);
        
        setTimeout(() => {
            if (document.body.contains(particle)) {
                document.body.removeChild(particle);
            }
        }, 1600);
    }
}

// 显示奢华Toast提示
function showLuxuryToast(message, type = 'info') {
    const toast = document.createElement('div');
    toast.className = `luxury-toast ${type}`;
    toast.textContent = message;
    
    const gradients = {
        success: 'linear-gradient(135deg, #a8edea 0%, #fed6e3 100%)',
        error: 'linear-gradient(135deg, #ff6b6b 0%, #ee5a52 100%)',
        info: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)'
    };
    
    toast.style.cssText = `
        position: fixed;
        top: 80px;
        left: 50%;
        transform: translateX(-50%) translateY(-100px);
        background: ${gradients[type] || gradients.info};
        color: white;
        padding: 16px 24px;
        border-radius: 32px;
        font-size: 14px;
        font-weight: 600;
        z-index: 1000;
        box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
        backdrop-filter: blur(20px);
        max-width: 320px;
        text-align: center;
        opacity: 0;
        transition: all 0.5s cubic-bezier(0.16, 1, 0.3, 1);
        border: 1px solid rgba(255, 255, 255, 0.2);
    `;
    
    document.body.appendChild(toast);
    
    setTimeout(() => {
        toast.style.opacity = '1';
        toast.style.transform = 'translateX(-50%) translateY(0)';
    }, 50);
    
    setTimeout(() => {
        toast.style.opacity = '0';
        toast.style.transform = 'translateX(-50%) translateY(-100px)';
        setTimeout(() => {
            if (document.body.contains(toast)) {
                document.body.removeChild(toast);
            }
        }, 500);
    }, 3500);
}

// 高级触觉反馈
function createLuxuryHapticFeedback(type = 'light') {
    if ('vibrate' in navigator) {
        switch(type) {
            case 'light':
                navigator.vibrate(10);
                break;
            case 'medium':
                navigator.vibrate([50, 20, 50]);
                break;
            case 'success':
                navigator.vibrate([100, 30, 100, 30, 100]);
                break;
            case 'error':
                navigator.vibrate([200, 100, 200]);
                break;
        }
    }
}

// 更新奢华习惯统计
function updateLuxuryHabitStats() {
    const totalHabits = document.querySelectorAll('.premium-habit-card').length;
    const completedHabits = document.querySelectorAll('.premium-habit-card.completed').length;
    
    // 更新统计数字
    const statNumbers = document.querySelectorAll('.stat-value');
    if (statNumbers.length >= 1) {
        statNumbers[0].textContent = `${completedHabits}/${totalHabits}`;
    }
    
    // 更新总体进度
    const completionRate = totalHabits > 0 ? Math.round((completedHabits / totalHabits) * 100) : 0;
    if (statNumbers.length >= 3) {
        statNumbers[2].textContent = `${completionRate}%`;
    }
}

// 处理高级设置变更
function handlePremiumSettingChange(toggle) {
    const settingItem = toggle.closest('.premium-setting-card');
    const settingName = settingItem.querySelector('.setting-title').textContent;
    
    createLuxuryHapticFeedback();
    
    // 保存设置
    localStorage.setItem(`elevateSetting_${settingName}`, toggle.checked);
    AppState.settings[settingName] = toggle.checked;
    
    switch (settingName) {
        case '智能提醒':
            if (toggle.checked) {
                showLuxuryToast('📱 智能提醒已启用', 'success');
                requestNotificationPermission();
            } else {
                showLuxuryToast('🔕 智能提醒已关闭', 'info');
            }
            break;
            
        case '深色主题':
            toggleLuxuryDarkMode(toggle.checked);
            break;
            
        case '云端同步':
            if (toggle.checked) {
                showLuxuryToast('☁️ 云端同步已启用', 'success');
            } else {
                showLuxuryToast('📱 云端同步已关闭', 'info');
            }
            break;
    }
}

// 请求通知权限
function requestNotificationPermission() {
    if ('Notification' in window && 'serviceWorker' in navigator) {
        Notification.requestPermission().then(function (permission) {
            if (permission === 'granted') {
                showLuxuryToast('✅ 通知权限已授予', 'success');
            }
        });
    }
}

// 切换奢华暗黑模式
function toggleLuxuryDarkMode(enabled) {
    if (enabled) {
        document.documentElement.setAttribute('data-theme', 'luxury-dark');
        showLuxuryToast('🌙 深色模式已启用', 'info');
    } else {
        document.documentElement.removeAttribute('data-theme');
        showLuxuryToast('☀️ 亮色模式已启用', 'info');
    }
}

// 更新豪华筛选标签
function updateLuxuryFilterTabs(activeTab) {
    document.querySelectorAll('.luxury-filter-tab').forEach(tab => {
        tab.classList.remove('active');
    });
    activeTab.classList.add('active');
}

// 筛选豪华项目
function filterLuxuryProjects(filter) {
    const projectItems = document.querySelectorAll('.premium-project-card');
    
    projectItems.forEach(item => {
        const status = item.querySelector('.project-status-luxury').textContent.trim();
        let shouldShow = false;
        
        switch (filter) {
            case '全部':
                shouldShow = true;
                break;
            case '进行中':
                shouldShow = status === '进行中';
                break;
            case '已完成':
                shouldShow = status === '已完成';
                break;
            case '计划中':
                shouldShow = status === '计划中';
                break;
        }
        
        if (shouldShow) {
            item.style.display = 'block';
            item.style.animation = 'luxuryFadeIn 0.5s cubic-bezier(0.16, 1, 0.3, 1)';
        } else {
            item.style.display = 'none';
        }
    });
}

// 切换奢华周期任务状态
function toggleLuxuryCycleTask(button) {
    const cycleItem = button.closest('.premium-cycle-card');
    const taskName = cycleItem.querySelector('.cycle-title').textContent;
    
    createLuxuryHapticFeedback();
    
    if (button.classList.contains('pending')) {
        button.classList.remove('pending');
        button.classList.add('completed');
        button.innerHTML = '<div class="btn-glow"></div><i class="fas fa-check"></i>';
        showLuxuryToast(`✅ 完成任务："${taskName}"`, 'success');
        
        playLuxuryCompletionAnimation(cycleItem);
        
    } else {
        button.classList.remove('completed');
        button.classList.add('pending');
        button.innerHTML = '<div class="btn-glow"></div><i class="fas fa-play"></i>';
        showLuxuryToast(`🔄 任务"${taskName}"已重置`, 'info');
    }
}

// 显示奢华添加模态框
function showLuxuryAddModal() {
    showLuxuryToast('🚧 高级功能开发中...', 'info');
}

// 加载用户偏好设置
function loadUserPreferences() {
    // 加载习惯状态
    document.querySelectorAll('.premium-habit-card').forEach(card => {
        const habitName = card.querySelector('.habit-title').textContent;
        const saved = localStorage.getItem(`elevateHabit_${habitName}`);
        if (saved === 'true') {
            const checkbox = card.querySelector('input[type="checkbox"]');
            checkbox.checked = true;
            card.classList.add('completed');
        }
    });
    
    // 加载设置状态
    document.querySelectorAll('.luxury-toggle-switch input').forEach(toggle => {
        const settingName = toggle.closest('.premium-setting-card').querySelector('.setting-title').textContent;
        const saved = localStorage.getItem(`elevateSetting_${settingName}`);
        if (saved !== null) {
            toggle.checked = saved === 'true';
            AppState.settings[settingName] = saved === 'true';
        }
    });
    
    updateLuxuryHabitStats();
}

// 保存奢华习惯数据
function saveLuxuryHabitData() {
    document.querySelectorAll('.premium-habit-card').forEach(card => {
        const habitName = card.querySelector('.habit-title').textContent;
        const isCompleted = card.classList.contains('completed');
        localStorage.setItem(`elevateHabit_${habitName}`, isCompleted);
    });
}

// 奢华应用启动动画
function animateLuxuryAppLaunch() {
    const elements = document.querySelectorAll('.luxury-inspiration-card, .premium-habit-card, .premium-goal-card, .premium-stat-card');
    
    elements.forEach((element, index) => {
        element.style.opacity = '0';
        element.style.transform = 'translateY(40px)';
        
        setTimeout(() => {
            element.style.transition = 'all 0.8s cubic-bezier(0.16, 1, 0.3, 1)';
            element.style.opacity = '1';
            element.style.transform = 'translateY(0)';
        }, index * 120);
    });
}

// 初始化背景动画
function initializeBackgroundAnimations() {
    // 粒子浮动效果已在CSS中实现
    console.log('✨ 奢华背景动画系统已启动');
}

// 创建页面过渡动画
function createPageTransition(page) {
    page.style.opacity = '0';
    page.style.transform = 'translateX(30px) scale(0.98)';
    
    setTimeout(() => {
        page.style.transition = 'all 0.6s cubic-bezier(0.16, 1, 0.3, 1)';
        page.style.opacity = '1';
        page.style.transform = 'translateX(0) scale(1)';
    }, 50);
}

// 更新页面特定功能
function updatePageSpecificFeatures(pageId) {
    switch (pageId) {
        case 'home':
            // 主页特定更新
            break;
        case 'projects':
            // 项目页特定更新
            break;
        case 'profile':
            // 个人页特定更新
            break;
    }
}

// 更新习惯状态徽章
function updateHabitStatusBadge(habitCard, status) {
    const statusBadge = habitCard.querySelector('.status-badge');
    if (statusBadge) {
        statusBadge.classList.remove('completed', 'pending');
        statusBadge.classList.add(status);
        statusBadge.textContent = status === 'completed' ? '已完成' : '待完成';
    }
}

// 创建成功波纹效果
function createSuccessRippleEffect(element) {
    const ripple = document.createElement('div');
    ripple.className = 'success-ripple';
    ripple.style.cssText = `
        position: absolute;
        top: 50%;
        left: 50%;
        width: 0;
        height: 0;
        border-radius: 50%;
        background: radial-gradient(circle, rgba(34, 197, 94, 0.3), transparent);
        transform: translate(-50%, -50%);
        pointer-events: none;
        animation: successRipple 1s ease-out forwards;
        z-index: 1;
    `;
    
    element.style.position = 'relative';
    element.appendChild(ripple);
    
    setTimeout(() => {
        if (element.contains(ripple)) {
            element.removeChild(ripple);
        }
    }, 1000);
}

// 创建各种动画效果的辅助函数
function createRotationAnimation(element) {
    element.style.transition = 'transform 0.3s cubic-bezier(0.16, 1, 0.3, 1)';
    element.style.transform = 'rotate(360deg)';
    setTimeout(() => {
        element.style.transform = 'rotate(0deg)';
    }, 300);
}

function createNavTabAnimation(element) {
    element.style.transform = 'scale(0.95)';
    setTimeout(() => {
        element.style.transition = 'transform 0.2s ease';
        element.style.transform = 'scale(1)';
    }, 100);
}

function createNavActiveAnimation(element) {
    const icon = element.querySelector('.tab-icon');
    if (icon) {
        icon.style.transition = 'transform 0.3s cubic-bezier(0.16, 1, 0.3, 1)';
        icon.style.transform = 'scale(1.2)';
        setTimeout(() => {
            icon.style.transform = 'scale(1.1)';
        }, 300);
    }
}

function createSparkleEffect(element) {
    for (let i = 0; i < 3; i++) {
        const sparkle = document.createElement('div');
        sparkle.innerHTML = '✨';
        sparkle.style.cssText = `
            position: absolute;
            top: 50%;
            left: 50%;
            pointer-events: none;
            font-size: 12px;
            z-index: 1000;
            animation: sparkleFloat 1s ease-out forwards;
            animation-delay: ${i * 0.1}s;
            transform: translate(-50%, -50%);
        `;
        
        element.style.position = 'relative';
        element.appendChild(sparkle);
        
        setTimeout(() => {
            if (element.contains(sparkle)) {
                element.removeChild(sparkle);
            }
        }, 1100);
    }
}

function createFilterAnimation(element) {
    element.style.transform = 'scale(1.05)';
    setTimeout(() => {
        element.style.transition = 'transform 0.2s ease';
        element.style.transform = 'scale(1)';
    }, 150);
}

function createPulseAnimation(element) {
    element.style.animation = 'luxuryPulse 0.4s ease-out';
    setTimeout(() => {
        element.style.animation = '';
    }, 400);
}

// 添加高级动画样式
const luxuryAnimationStyles = document.createElement('style');
luxuryAnimationStyles.textContent = `
    @keyframes luxuryCelebrationFloat {
        0% {
            opacity: 1;
            transform: translate(-50%, -50%) scale(1);
        }
        100% {
            opacity: 0;
            transform: translate(calc(-50% + var(--end-x)), calc(-50% + var(--end-y))) scale(0.3);
        }
    }
    
    @keyframes successRipple {
        0% {
            width: 0;
            height: 0;
            opacity: 0.6;
        }
        100% {
            width: 200px;
            height: 200px;
            opacity: 0;
        }
    }
    
    @keyframes sparkleFloat {
        0% {
            opacity: 0;
            transform: translate(-50%, -50%) scale(0.5);
        }
        50% {
            opacity: 1;
            transform: translate(-50%, -70%) scale(1);
        }
        100% {
            opacity: 0;
            transform: translate(-50%, -90%) scale(0.5);
        }
    }
    
    @keyframes luxuryPulse {
        0% { transform: scale(1); }
        50% { transform: scale(1.05); }
        100% { transform: scale(1); }
    }
    
    @keyframes luxuryFadeIn {
        0% {
            opacity: 0;
            transform: translateY(20px) scale(0.98);
        }
        100% {
            opacity: 1;
            transform: translateY(0) scale(1);
        }
    }
`;
document.head.appendChild(luxuryAnimationStyles);

// 导出API供调试使用
window.ElevateApp = {
    switchToPremiumPage,
    loadDailyInspiration,
    showLuxuryToast,
    createLuxuryHapticFeedback,
    updateLuxuryHabitStats,
    AppState
};

// 防止页面滚动弹跳和多点触控
document.addEventListener('touchstart', function(e) {
    if (e.touches.length > 1) {
        e.preventDefault();
    }
});

let lastTouchEnd = 0;
document.addEventListener('touchend', function(e) {
    const now = (new Date()).getTime();
    if (now - lastTouchEnd <= 300) {
        e.preventDefault();
    }
    lastTouchEnd = now;
}, false);

console.log('🚀 ELEVATE - 高端生活管理助手 JavaScript 加载完成！');
console.log('✨ 支持功能：手势切换、高级触觉反馈、PWA支持、奢华主题');
console.log('👆 操作提示：左右滑动切换页面，点击底部导航快速跳转');